<?php
/**
 * Description: 列方程模块
 * User: devforma
 * Date: 16/7/28
 * Time: 10:10
 */
require_once __DIR__ . '/ProcessExerciseBase.class.php';

class LiefangchengModule extends ProcessExerciseBase {

    /**
     * 设置作业类型
     */
    protected function setExerciseType() {
        $this->data['exercise_type'] = 30;
    }

    /**
     * 设置作业题目内容
     */
    protected function setExerciseQuestion() {
        global $cmsdb;

        //获取所有题目
        $questionStr = implode(',', $this->questionIds);
        $sql = "SELECT * FROM `original_primary_question` WHERE `id` IN ({$questionStr}) ORDER BY FIELD (`id`, {$questionStr})";
        $questionInfo = (array)$cmsdb->getResults($sql);

        foreach ($questionInfo as $q) {
            $this->data['question'][] = array(
                'question_id' => (int)$q->id,
                'question'    => $q->content,
                'answer'      => $q->right_answer
            );
        }
    }

    /**
     * 设置提交权限
     */
    protected function setSubmitPriv() {
        parent::setSubmitPriv();
    }

    /**
     * 设置用户答案
     * 
     */
    protected function setUserAnswer() {
        global $uddb;

        //按照题序获取答题记录
        $sql = "SELECT * FROM `history_user_primary_question` WHERE `exercise_id`=:eid AND `user_id`=:uid";
        $questionRecord = (array)$uddb->getResults($sql, [':eid' => $this->exerciseId, ':uid' => $this->userId]);

        foreach ($questionRecord as $record) {
            $this->data['user_answer'][$record->question_id] = [
                'question_id' => (int)$record->question_id,
                'action_time' => $record->acting_time,
                'content'     => $record->user_answer
            ];
        }

        //需要题目与答案的合并
        $this->shouldMergeQA = true;
    }

    /**
     * 设置作业的统计信息
     */
    protected function setSummary() {
        $this->data['summary'] = json_decode($this->userExerciseRecord->summary);
    }

    /**
     * 校验参数
     *
     * @param array $args 参数
     * @return bool
     */
    public function validateArgs($args) {
        if (!empty($args['answer_content']) && !empty($args['duration'])) {
            $this->submitArgs = $args;
            return true;
        }

        return false;
    }

    /**
     * 提交作业的额外操作
     */
    protected function doExtra() {}

    /**
     * 设置作业记录的状态
     */
    protected function setSubmitStatus() {
        if ($this->exerciseInfo->end_time > $this->now)
            $this->submitExerciseRecord['status'] = 1; //已完成
        else
            $this->submitExerciseRecord['status'] = 5; //过期完成
    }

    /**
     * 保存答题记录记作业统计信息
     */
    protected function saveQuestionRecordsAndSetSubmitSummary() {
        global $uddb;

        $answers = json_decode($this->submitArgs['answer_content']);

        $right = $total = 0;
        foreach ($answers as $answer) {
            if ($answer->is_right)
                $right++;

            $total++;

            //构造答题记录
            $record = array(
                'question_id' => $answer->question_id,
                'exercise_id' => $this->exerciseId,
                'user_id'     => $this->userId,
                'acting_time' => $this->now,
                'user_answer' => $answer->answer,
                'is_right'    => $answer->is_right,
                'status'      => 1
            );
            $uddb->insert('history_user_primary_question', $record);
        }

        //更新已做人数
        $this->updateXingcePersonsNum();

        $this->submitExerciseRecord['summary'] = json_encode([
            'position'     => $this->getXingcePersonsNum(),
            'duration'     => (int)$this->submitArgs['duration'],
            'accuracy'     => round($right/$total, 3),
            'avg_duration' => round($this->submitArgs['duration']/$total)
        ]);
    }

    /**
     * 获取自测题目
     *
     * @param array $ids
     * @param array $userAnswers
     * @return array
     */
    protected function getSelfTestQuestions($ids, &$userAnswers) {
        global $cmsdb;

        //获取所有题目
        $questionStr = implode(',', $ids);
        $sql = "SELECT * FROM `original_primary_question` WHERE `id` IN ({$questionStr}) ORDER BY FIELD (`id`, {$questionStr})";
        $questionInfo = (array)$cmsdb->getResults($sql);

        $list = [];
        foreach ($questionInfo as $q) {
            if (isset($userAnswers[$q->id])) {
                $list[] = array(
                    'question_id' => (int)$q->id,
                    'question'    => $q->content,
                    'answer'      => $q->right_answer,
                    'user_answer' => $userAnswers[$q->id]
                );
            } else {
                $list[] = array(
                    'question_id' => (int)$q->id,
                    'question'    => $q->content,
                    'answer'      => $q->right_answer
                );
            }
        }

        return $list;
    }

    /**
     * 提交自测题目
     *
     * @param array $args
     * @return array
     */
    public function submitSelfTest($args) {
        global $uddb;

        $answers = json_decode($args['answer_content']);

        $right = $total = 0;
        $records = [];
        foreach ($answers as $answer) {
            if ($answer->is_right)
                $right++;

            $total++;

            //构造答题记录
            $record = array(
                'question_id' => $answer->question_id,
                'exercise_id' => 0,
                'user_id'     => $args['user_id'],
                'acting_time' => $this->now,
                'user_answer' => $answer->answer,
                'is_right'    => $answer->is_right,
                'status'      => 1
            );
            $uddb->insert('history_user_primary_question', $record);

            $records[] = $uddb->lastInsertId();
        }

        $summary = [
            'duration'     => (int)$args['duration'],
            'accuracy'     => round($right/$total, 3),
            'avg_duration' => round($args['duration']/$total)
        ];

        //自测记录
        $uddb->insert('history_user_primary_selftest', [
            'user_id'     => $args['user_id'],
            'type_id'     => 30,
            'action_time' => $this->now,
            'records'     => implode(',', $records),
            'summary'     => json_encode($summary)
        ]);

        $summary['selftest_id'] = (int)$uddb->lastInsertId();

        return $summary;
    }
}